<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/5
 * Time: 17:52
 */

namespace common\controllers;

use Yii;
use yii\base\ErrorException;
use yii\helpers\ArrayHelper;
use yii\web\Controller;

class BaseController extends Controller
{
    /**
     * @var array 用户信息
     */
    protected $userInfo;

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        if (Yii::$app->request->isAjax) {
            header('Content-type:text/javascript;');
        }
    }


    /**
     * ajax返回
     * @param array $return
     * @return string
     */
    public function ajaxArray($return = [])
    {
        $response = [
            'msg' => '返回处理异常',
            'status' => false,
            'data' => [],
            'redirectUrl' => '',
        ];
        if ($response) {
            $response = array_merge($response, (array)$return);
        }
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return $response;
    }

    /**
     * 成功处理
     * @param string $msg 提示信息
     * @param array $data 数据
     * @param string $redirectUrl 跳转页面
     * @param string $callback JS回调
     * @return array
     */
    public function success($msg, $data = [], $redirectUrl = '', $callback = '')
    {
        if (Yii::$app->request->isAjax) {
            return $this->ajaxReturn($msg, 'SUCCESS', $data, $redirectUrl, $callback);
        } else {
            Yii::$app->getSession()->setFlash('message', $msg);
        }
    }


    /**
     * ajax返回
     * @param string $msg 提示信息
     * @param string $status 状态
     * @param array $data 数据
     * @param string $redirectUrl 跳转页面
     * @param string $callback JS回调
     * @return array
     */
    public static function ajaxReturn($msg, $status = 'SUCCESS', $data = [], $redirectUrl = '', $callback = '')
    {
        $response = [
            'msg' => $msg,
            'status' => $status,
            'data' => $data,
            'redirectUrl' => $redirectUrl,
            'callback' => $callback,
        ];
        return $response;
    }

}